package com.mr.productclient.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Class: JsonUtil
 * User (作者):MRui
 * TODO (描述)：json转换工具类
 * Date 2018.09.25 23:23
 */
public class JsonUtil {


    private static ObjectMapper objectMapper = new ObjectMapper();
    private static GsonBuilder gsonBuilder = new GsonBuilder();
    /**
    * User (作者): MRui
    * TODO (描述)：利用gson对象转Json
    * Data：2018.09.25 23:25
    */
    public static String gsonToJson(Object object){
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return gson.toJson(object);
    }

    /**
     * User (作者): MRui
     * TODO (描述)：利用jackson对象转Json
     * Data：2018-11-11 21:38
     */
    public static String jacksonToJson(Object object){
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * User (作者): MRui
     * TODO (描述)：利用jacksonjson转对象
     * Data：2018-11-11 21:38
     */
    public static <T>T jacksonFromJson(String json,Class<T> object){
        try {
//            SerializationFeature.FAIL_ON_EMPTY_BEANS
            return objectMapper.readValue(json, object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
